package core;

import protocal.Constants;
import protocal.DeviceKick;
import protocal.GroupNotification;
import protocal.IMMessage;
import protocal.Message;
import protocal.MessageACK;
import protocal.MessageInputing;
import protocal.MessageOnlineState;
import protocal.MessagePeerACK;

public class ReceiveProcessor extends Thread {
	private GimCore core;
	private GimMessageHandle handle;
	
	public ReceiveProcessor(GimCore core, GimMessageHandle handle) {
		this.core = core;
		this.handle = handle;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(!Thread.interrupted()) {
			Message m = core.receive();
			if(m == null) {
				core.restart();
				break;
			}
			
			switch(m.cmd) {
			case Constants.MSG_IM:
				IMMessage im = (IMMessage) m.body;
				handle.handleIMMessage(im);
				core.insertInQueue(m);
				
				//回送ack确认消息已经收到，从离线库移除
				Message m1 = new Message();
				m1.cmd = Constants.MSG_PEER_ACK;
				MessagePeerACK mpa = new MessagePeerACK();
				mpa.msgid = im.msgid;
				mpa.sender = im.sender;
				mpa.receiver = im.receiver;
				m1.body = mpa;
				core.messageInQueue(m1);
				
				break;
			case Constants.MSG_GROUP_IM:
				IMMessage im1 = (IMMessage) m.body;
				handle.handleGroupIMMessage(im1);
				core.insertInQueue(m);
				
				//回送ack确认消息已经收到，从离线库移除
				Message m2 = new Message();
				m2.cmd = Constants.MSG_PEER_ACK;
				MessagePeerACK mpa1 = new MessagePeerACK();
				mpa1.msgid = im1.msgid;
				mpa1.sender = im1.sender;
				mpa1.receiver = im1.receiver;
				m2.body = mpa1;
				core.messageInQueue(m2);
				
				break;
			case Constants.MSG_GROUP_NOTIFICATION:
				GroupNotification gn = (GroupNotification) m.body;
				handle.handleGroupNotification(gn);
				break;
			case Constants.MessageInputing:
				MessageInputing mi = (MessageInputing) m.body;
				handle.handleMessageInputting(mi);
				break;
			case Constants.MSG_PONG:
				core.setLastPongTime(System.currentTimeMillis());
				break;
			case Constants.MSG_DEVICE_KICK:
				DeviceKick dk = (DeviceKick) m.body;
				core.close();
				handle.handleDeviceKick(dk);
				break;
			case Constants.MSG_ONLINE_STATE:
				MessageOnlineState mos = (MessageOnlineState) m.body;
				handle.handleOnlineState(mos);
				break;
			case Constants.MSG_ACK:
				//将消息标记为发送成功
				MessageACK ma = (MessageACK)m.body;
				handle.handleMessageAck(ma);
				core.getGdb().markMsgSendSuccess(ma.seq);
				break;
			default:
				break;
			}
		}
	}

}
